package kr.saeildamil.androidstudy_second25;

import java.io.File;
import java.util.ArrayList;

import kr.saeildamil.androidstudy_second.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class FileExplorer extends Activity {
	String mCurrent;	//현재 경로
	String mRoot;		//mnt/sdcard
	TextView mCurrentTxt;	//현재 경로 표시
	ListView mFileList;		//현재 경로상의 파일 정보 리스트
	ArrayAdapter<String>mAdapter;	//파일 정보들
	ArrayList<String>arFiles;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch25_fileexplorer);
		
		mCurrentTxt=(TextView) findViewById(R.id.current);
		mFileList=(ListView) findViewById(R.id.filelist);
		
		arFiles=new ArrayList<String>();
		mRoot=Environment.getExternalStorageDirectory().getAbsolutePath();
		mCurrent=mRoot;
		
		mAdapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arFiles);
		mFileList.setAdapter(mAdapter);
		mFileList.setOnItemClickListener(mItemClickListener);
		
		refreshFiles();
	}
	
	public void mOnClick(View v){
		switch (v.getId()) {
		case R.id.btnroot:
			if(mCurrent.compareTo(mRoot)!=0){
				mCurrent=mRoot;
				refreshFiles();
			}
			break;

		case R.id.btnup:
			if(mCurrent.compareTo(mRoot)!=0){
				int end=mCurrent.lastIndexOf("/");
				String upPath=mCurrent.substring(0, end);
				mCurrent=upPath;
				refreshFiles();
			}
			break;
		}
	}
	private void refreshFiles() {
		mCurrentTxt.setText(mCurrent);
		arFiles.clear();
		File current=new File(mCurrent);//현재 작업중인 폴더에 있는 파일정보를 얻기 위해 File 객체 생성
		
		String[] files=current.list();
		if(files!=null){
			for(String fileInfo:files){
				File file=new File(mCurrent+"/"+fileInfo);
				String Name="";
				if(file.isDirectory()){
					Name="["+fileInfo+"]";
				}else{
					Name=fileInfo;
				}
				arFiles.add(Name);
			}
		}
		mAdapter.notifyDataSetChanged();
	}
	AdapterView.OnItemClickListener mItemClickListener=new AdapterView.OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long arg3) {
			String name=arFiles.get(position);
			if(name.startsWith("[") && name.endsWith("]")){
				name=name.substring(1, name.length()-1);
				Toast.makeText(FileExplorer.this, "디렉터리"+name, 1).show();
				mCurrent=mCurrent+"/"+name;
				refreshFiles();
			}else{
				Toast.makeText(FileExplorer.this, name, 1).show();
			}
			
		}
	};
}
